import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../services/search.dart';
import '../utils/dio_util.dart';
import '../widget/my_loading.dart';
import '../widget/empty_page.dart';
import '../widget/my_image.dart';

class ProductListPage extends StatefulWidget {
  final Map arguments;

  ProductListPage({Key key, this.arguments}) : super(key: key);

  _ProductListPageState createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  //配置search搜索框的值
  TextEditingController _search=TextEditingController();
  //Scaffold key
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  //用于上拉分页 listview 的控制器
  ScrollController _scrollController = ScrollController();

  //分页
  int _page = 1;

  //每页有多少条数据
  int _pageSize = 8;

  //数据
  List _productList = [];

  bool _isGrid=true;//是否是网格布局
  String _priceOrder = "price desc";//价格排序
  String _salesOrder = "sall desc";//销量排序

  //解决重复请求的问题
  bool _flag = true;
  bool _isNew;//是否是新品
  //是否有数据
  bool _hasMore = true;

  //是否有搜索的数据
  bool _hasData = true;

  /*二级导航数据*/
  List _subHeaderList = [
    {
      "id": 1,
      "title": "栏目名称",
      "fileds": "all",
      "sort":'sall desc', //排序
    },
    {"id": 2, "title": "价格", "fileds": 'price', "sort": ''},
    {"id": 3, "title": "销量", "fileds": 'salecount', "sort": ''},

    {"id": 4, "title": "新品","fileds": 'isNew'}
  ];

  //二级导航选中判断
  int _selectHeaderId = 1;




  //cid

  //keywords
  String _categoryName;//栏目名称
  var _cid;

  var _keywords='';

  @override
  void initState() {
    super.initState();
    _cid = widget.arguments["categoryId"];
    _keywords = widget.arguments["queryCondition"];
    _categoryName = widget.arguments["categoryName"];
    setState(() {
      _subHeaderList.first['title']=_categoryName;
    });
    //给search框框赋值
    _search.text = _keywords;
    _getProductListData();
    //监听滚动条滚动事件
    _scrollController.addListener(() {
      //_scrollController.position.pixels //获取滚动条滚动的高度
      //_scrollController.position.maxScrollExtent  //获取页面高度
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (_flag && _hasMore) {
          _getProductListData();
        }
      }
    });
  }

  //获取商品列表的数据
  _getProductListData() async {
    setState(() {
      _flag = false;
    });
    String api = '/api/mall/product/pageList.service';
    Map<String, dynamic> param;
    param = {
      'queryCondition':_keywords == null?'':_keywords,
      'isNew':_isNew==null?'':(_isNew==false?'0':'1'),
      'priceOrder':_priceOrder,
      'salesOrder':_priceOrder,
      'pageIndex': _page,
      'pageSize': _pageSize,
      'categoryId':_cid
    };
    // print(api);
    var http = DioUtil();
    await http.get(api, data: param).then((res) {
      if (res['code'] == 200) {
        var result = res['result'];
        //判断是否有搜索数据
        if (result.length == 0 && _page == 1) {
          setState(() {
            _hasData = false;
          });
        } else {
          _hasData = true;
        }
        //判断最后一页有没有数据
        if (result.length < _pageSize) {
          setState(() {
            _productList.addAll(result);
            _hasMore = false;
            _flag = true;
          });
        } else {
          setState(() {
            _productList.addAll(result);
            _page++;
            _flag = true;
          });
        }
      }
    });
  }

  //显示加载中的圈圈
  Widget _showMore(index) {
    if (_hasMore) {
      return (index == _productList.length - 1) ? MyLoadding() : Text("");
    } else {
      return (index == _productList.length - 1)
          ? Text("--我是有底线的--")
          : Text("");
    }
  }

  //竖排商品列表
  Widget _productListWidget() {
    if (_productList.length > 0) {
      return SliverList(
        delegate: new SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  String image = _productList[index]['image'];
                  return Container(
                    width: 700.w,
                    margin: EdgeInsets.only(left: 25.w),
                    child: Column(
                      children: <Widget>[
                        InkWell(
                          onTap: () {
                            Navigator.of(context).pushNamed('/productContent',
                                arguments: {
                                  'productId': _productList[index]['productId']
                                });
                          },
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: 180.w,
                                height: 180.h,
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(15.sp),
                                  child: MyImage(imgSrc: image),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: 180.h,
                                  margin: EdgeInsets.only(left: 10),
                                  // color: Colors.red,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text("${_productList[index]['productName']}",
                                          maxLines: 1, overflow: TextOverflow.ellipsis),
                                      RichText(
                                        text: TextSpan(
                                            children:[
                                              TextSpan(
                                                text: '￥',
                                                style:
                                                TextStyle(color: Colors.red, fontSize: 30.sp,    fontWeight: FontWeight.bold,),
                                              ),
                                              TextSpan(
                                                text:"${_productList[index]['price']}",
                                                style:
                                                TextStyle(color: Colors.red, fontSize: 38.sp,    fontWeight: FontWeight.bold,),
                                              )
                                            ]
                                        ),
                                      ),

                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          RichText(
                                            text: TextSpan(
                                                children:[
                                                  TextSpan(
                                                    text: '￥',
                                                    style:
                                                    TextStyle(color: Colors.black, fontSize: 30.sp,    fontWeight: FontWeight.bold,),
                                                  ),
                                                  TextSpan(
                                                    text:"${_productList[index]['vipPrice']}",
                                                    style:
                                                    TextStyle(color: Colors.black, fontSize: 35.sp,    fontWeight: FontWeight.bold,),
                                                  )
                                                ]
                                            ),
                                          ),

                                          Text('已售${_productList[index]['sales']}件',style: TextStyle(
                                              color: Colors.grey,
                                              fontSize: 25.sp
                                          ),)
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        Divider(height: 20),
                        _showMore(index)
                      ],
                    ),
                  );
            }, childCount: _productList.length, //30个列表项
        ),
      );

    } else {
      //加载中
      return SliverToBoxAdapter(
        child: MyLoadding(),
      );
    }
  }

  //横排商品列表
  Widget _productGridWidget() {
    if (_productList.length > 0) {
      return SliverGrid(
        gridDelegate: new SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 650.w,
          mainAxisSpacing: 0.w, //主轴中间间距
          crossAxisSpacing: 0.w, //副轴中间间距
          childAspectRatio: 0.7, //item 宽高比
        ),
        delegate: new SliverChildBuilderDelegate(
              (BuildContext context, int index) {
            String image = _productList[index]['image'];
            return InkWell(
              onTap: () {
                Navigator.of(context).pushNamed('/productContent',
                    arguments: {
                      'productId': _productList[index]['productId']
                    });
              },
              child: Container(
                margin: EdgeInsets.only(left: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      width: 325.w,
                      height: 325.w,

                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.sp),
                        child: MyImage(imgSrc: image,fit:BoxFit.fill),
                      ),
                    ),
                    SizedBox(height:15.w),
                    Text("${_productList[index]['productName']}",
                        maxLines: 1, overflow: TextOverflow.ellipsis),
                    SizedBox(height:5.w),
                    RichText(
                      text: TextSpan(
                        children:[
                          TextSpan(
                            text: '￥',
                            style:
                            TextStyle(color: Colors.red, fontSize: 30.sp,    fontWeight: FontWeight.bold,),
                          ),
                          TextSpan(
                            text:"${_productList[index]['price']}",
                            style:
                            TextStyle(color: Colors.red, fontSize: 38.sp,    fontWeight: FontWeight.bold,),
                          )
                        ]
                      ),
                    ),
                    SizedBox(height:5.w),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('￥${_productList[index]['vipPrice']}',style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 35.sp
                        ),),

                        Text('已售${_productList[index]['sales']}件',style: TextStyle(
                            color: Colors.grey,
                            fontSize: 25.sp
                        ),)
                      ],
                    )
                  ],
                ),
              ),
            );
          }, childCount: _productList.length, //30个列表项
        ),
      );

    } else {
      //加载中
      return SliverToBoxAdapter(
        child: MyLoadding(),
      );
    }
  }

  //导航改变的时候触发
  _subHeaderChange(id) {
    print(_priceOrder);
    if (id == 4) {
      setState(() {
        _isNew=!_isNew;
        _salesOrder='';
        _priceOrder='';

      });
    } else if(id==3){
      setState(() {
        _salesOrder =_salesOrder=='sall desc'?'sall asc':'sall desc';
        _isNew=false;
      });

    }else if(id==2){
      setState(() {
        _priceOrder =_priceOrder=='price desc'?'price asc':'price desc';
      });
    }else if(id==1){
      //综合，初始化
      setState(() {
        _isNew=false;
        _salesOrder='sall asc';
        _priceOrder='price asc';
      });
    }

    //重置分页
    _page = 1;
    //重置数据
    _productList = [];
    _selectHeaderId = id;
    //回到顶部
    _scrollController.jumpTo(0);
    //重置_hasMore
    _hasMore = true;
    //重新请求
    _getProductListData();
  }

  //显示header Icon
  Widget _showIcon(id) {
    print(id);
    if(id==2||id==3){
      if(_priceOrder=='price asc'||_salesOrder=='sall asc'){
        return Icon(Icons.arrow_drop_down);
      }else{
//        return Icon(Icons.);
        return Icon(Icons.arrow_drop_up);
      }
    }else{
      return Text('');
    }






  }

  //筛选导航
  Widget _subHeaderWidget() {
    return Container(
      width: 750.w,
      height: 80.h,
      // color: Colors.red,
      decoration: BoxDecoration(
        color: Colors.white,
          border: Border(
              bottom: BorderSide(
                  width: 1, color: Colors.white))),
      child: Row(
        children: _subHeaderList.map((value) {
          return Expanded(
            flex: 1,
            child: InkWell(
              child: Padding(
                padding: EdgeInsets.fromLTRB(0, 16.h, 0, 16.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "${value["title"]}",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: (_selectHeaderId == value["id"])
                              ? Colors.red
                              : Colors.black54),
                    ),
                    _showIcon(value["id"])
                  ],
                ),
              ),
              onTap: () {
                _subHeaderChange(value["id"]);
              },
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _searchWidget() {
    return Container(
      height: 120.w,
      width: 750.w,
      padding: EdgeInsets.symmetric(horizontal: 25.w,vertical: 20.w),
      decoration: BoxDecoration(
        color: Colors.red
      ),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 600.w,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(30.w)),
            child: TextField(
              controller:_search,
                textInputAction:TextInputAction.search,
              style: TextStyle(
                fontSize: 28.sp
              ),
              autofocus: false,
              decoration: InputDecoration(
//                contentPadding:EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
                prefixIcon: Icon(Icons.search,color: Colors.grey,),
                suffix: _keywords==null||_keywords.isEmpty?Text(''):GestureDetector(
                  onTap: (){
                    setState(() {
                      _search.text = '';
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.only(top:60.w),
                    child: Icon(Icons.close,color: Colors.grey,),
                  ),
                ),
                hintText: '搜索商品名称',
                hintStyle: TextStyle(
                  color: Colors.grey
                ),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(30),
                    borderSide: BorderSide.none),
              ),
              onSubmitted: (text) {
                  setState(() {
                    _cid='';
                  });
                _getProductListData();
              },
              onChanged: (value) {
                setState(() {
                  _keywords = value;
                });
              },
            ),
          ),
          AnimatedSwitcher(
            duration: const Duration(milliseconds: 500),
            transitionBuilder: (Widget child, Animation<double> animation) {
              //执行缩放动画
              return ScaleTransition(child: child, scale: animation);
            },
            child:IconButton(
              key: UniqueKey(),
              icon: Icon(_isGrid?Icons.grid_on:Icons.view_list,color: Colors.white,size: 50.sp,),
              onPressed: () {
                SearchServices.setHistoryData(_keywords);
                _subHeaderChange(1);
                setState(() {
                  _isGrid=!_isGrid;
                });
              },
            ),
          ),

        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.red,
          leading: BackButton(
            color: Colors.white,
          ),
          title: Text('商品列表',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 30.sp,
                  fontWeight: FontWeight.bold)),
        ),
        body: Container(
          color: Colors.white,
          child: Column(
            children: [
              _searchWidget(),
              _subHeaderWidget(),
              Expanded(
                child:  _hasData==true?Container(
                  width: 750.w,
                  padding: EdgeInsets.all(10.w),
                  child: CustomScrollView(
                    controller: _scrollController,
                    physics: BouncingScrollPhysics(),
                    slivers: [
                      _isGrid?_productGridWidget():_productListWidget(),
                    ],
                  ),
                ):EmptyPage(title: '商品列表为空',),
              ),
            ],
          ),
        ));
  }
}
